<template>
    <div>
        <div class="flex items-center justify-between pb-[1rem] px-[0.5rem]">
            <div class="flex items-center justify-between gap-[1.5rem] ">
                <div v-for="item in tabList" :key="item.value"
                    class="text-[1rem] font-[Inter] font-normal leading-[1.5rem] text-[#4B5563] cursor-pointer"
                    :class="item.value === activeTab ? '!text-[#000]' : ''" @click="handleTabClick(item.value)">{{
                    item.name }}</div>
            </div>
            <el-dropdown trigger="click">
                <div class="h-[2.25rem] rounded-[9999px] bg-[#FFFFFF] text-[#374151] flex items-center justify-center px-[1rem] py-[0.5rem] text-[0.875rem] font-[Inter] font-normal leading-[1.25rem] cursor-pointer hover:bg-gray-50"
                    style="border: 1px solid #E5E7EB;">
                    {{ currentSort }}
                    <el-icon class="ml-[0.75rem]">
                        <ArrowDown class="w-[0.75rem] h-[0.5rem]" />
                    </el-icon>
            </div>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item @click="handleSort('latest')">最新发布</el-dropdown-item>
                        <el-dropdown-item @click="handleSort('hot')">最热门</el-dropdown-item>
                        <el-dropdown-item @click="handleSort('recommend')">推荐</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
        <!-- <div class="flex justify-between">
            <div class="flex items-center gap-[0.5rem]">
                
                
            </div>
            <div class="flex items-center gap-[0.5rem] my-[1.5rem]">
                <span class="text-[0.875rem] font-[Inter] font-normal leading-[1.25rem] text-[#6B7280]">日期</span>
                <span class="w-[5rem] h-[1.75rem] bg-[#F3F4F6] rounded-[9999px] text-[0.875rem] font-[Inter] font-normal leading-[1.25rem] text-[#111827] ml-[1rem] flex items-center justify-center">最新发布</span>
            </div>
        </div> -->
        <div class="flex flex-col gap-[1rem] mb-[1.5rem]">
            <ArticleCard 
                v-for="item in list" 
                :key="item.id"
                :article="item"
            />
        </div>
        <!-- 分页组件 -->
        <Pagination :total="total" :pageSize="pageSize" v-model:currentPage="currentPage" />

        <!-- 投诉弹窗 -->
        <Complaint 
            v-model="showComplaint"
            :post-id="currentPostId"
            @close="showComplaint = false"
        />

        <!-- 文件下载弹窗 -->
        <FileDownload
            v-model="showFileDownload"
            :file-url="currentFileUrl"
            :file-name="currentFileName"
            @close="showFileDownload = false"
            @download="handleFileDownload"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, computed, shallowRef } from 'vue';
import { useRouter } from 'vue-router'
import { formatRelativeTime } from '@/utils/time'
import Pagination from '@/components/Pagination/index.vue'
import { ArrowDown } from '@element-plus/icons-vue'
import Complaint from './Complaint.vue'
import CommentInput from '@/components/CommentInput/index.vue'
import { message } from '@/utils/message'
import { ElImage } from 'element-plus'
import FileDownload from '@/components/FileDownload/index.vue'
import ArticleCard from '@/components/ArticleCard/index.vue'

const router = useRouter()

const tabList = ref([
    {
        name: '热门',
        value: 'hot',
    },
    {
        name: '精华',
        value: 'essence',
    },
    {
        name: '全部',
        value: 'all',
    },
    {
        name: '关注',
        value: 'follow',
    },
    {
        name: '官方专栏',
        value: 'official',
    },
    
])
const activeTab = ref('hot');
const handleTabClick = (value: string) => {
    activeTab.value = value;
}

// 定义评论和回复的类型接口
interface Reply {
  id: number;
  author: string;
  avatar: string;
  content: string;
  time: string;
  likes: number;
  replyTo: string;
}

interface Comment {
  id: number;
  author: string;
  avatar: string;
  content: string;
  time: string;
  likes: number;
  replyTo: string;
  replies: Reply[];
}

// 定义帖子类型接口
interface Post {
  id: number;
  author: string;
  authorAvatar: string;
  authorLevel: string;
  title: string;
  description: string;
  releaseTime: string;
  comment: number;
  like: number;
  collect: number;
  tags: string[];
  likeNames: string[];
  showComment: boolean;
  images: string[];
  files: string[];
  commentList: Comment[];
}

const baseList = ref<Post[]>([
    {   
        id: 1,
        author: '沅仁',
        authorAvatar: '/public/images/avatar.png',
        authorLevel: '9',
        title: '20:00 到，第 9 年的 "418 活动"正式收官！',
        description: '今天，我们迎来了 70000 名朋友，中正式完成了从 2765 元到 3365 元的价格阶梯，你看到了吗？之后新人仍然可以加入，只是价格略高一点。',
        releaseTime: '2025-05-23 10:00',
        comment: 272,
        like: 47,
        collect: 3,
        tags: ['自媒体','up主'],
        likeNames:['XXX','YYY','ZZZ'],
        showComment: false,
        images:['https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D'],
        files:[],
        commentList:[
            {
                id: 101,
                author: '张三',
                avatar: '/public/images/avatar.png',
                content: '这是一条评论内容',
                time: '2024-01-01 12:00:00',
                likes: 10,
                replyTo: '张三',
                replies: [
                    {
                        id: 201,
                        author: '李四',
                        avatar: '/public/images/avatar.png', 
                        content: '这是一条回复',
                        time: '2024-01-01 12:30:00',
                        likes: 5,
                        replyTo: '张三',
                    }
                ]
            },
            {
                id: 102,
                author: '王五',
                avatar: '/public/images/avatar.png',
                content: '又一条评论内容',
                time: '2024-01-01 13:00:00', 
                likes: 8,
                replyTo: '张三',
                replies: []
            }
        ],
    },
    {   
        id: 2,
        author: '小明',
        authorAvatar: '/public/images/avatar.png',
        authorLevel: '7',
        title: '欢迎 70000 位朋友@public c/a*，奔',
        description: '过去 8 年的时间，从 0 到 70000+，每一位朋友的加入，都是一次双向奔赴，感谢新朋友的信任，也感谢老朋友的陪伴行动，你们的每一次选择，都在让"生财春天"这条船更稳。',
        releaseTime: '2025-05-21 10:00',
        comment: 244,
        like: 35,
        collect: 2,
        tags: ['小红书'],
        likeNames:['XXX','YYY','ZZZ'],
        showComment: false,
        images:['https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D'],
        files:[],
        commentList:[],
    },
    {   
        id: 3,
        author: '张三',
        authorAvatar: '/public/images/avatar.png',
        authorLevel: '5',
        title: '分享我的学习经验',
        description: '最近在学习前端开发，分享一下我的学习心得...',
        releaseTime: '2025-05-20 15:30',
        comment: 156,
        like: 89,
        collect: 12,
        tags: ['小蓝书'],
        likeNames:['XXX','YYY','ZZZ'],
        showComment: false,
        images:['https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D',],
        files:['http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip'],
        commentList:[],
    },
    {   
        id: 4,
        author: '李四',
        authorAvatar: '/public/images/avatar.png',
        authorLevel: '6',
        title: '技术讨论：Vue3 vs React',
        description: '大家来讨论一下Vue3和React的优缺点...',
        releaseTime: '2025-05-19 09:15',
        comment: 342,
        like: 167,
        collect: 45,
        tags: [],
        likeNames:['XXX','YYY','ZZZ','XXXX'],
        showComment: false,
        images:['https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D','https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/97d400be206d491da31843b9abadb5da~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5rWq6YGP:q75.awebp?rk3s=f64ab15b&x-expires=1750044673&x-signature=kU4a72Bys8hyvM8OsmPOS5ouHw8%3D'],
        files:['http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip','http://xy.xiaoxu.wiki/chromedriver-win64.zip',],
        commentList:[],
    }
]);

// 生成100条数据
const allList = ref<Post[]>(Array.from({ length: 100 }, (_, index) => {
    const baseItem = baseList.value[index % baseList.value.length];
    return {
        ...baseItem,
        title: `${baseItem.title} (${index + 1})`,
        comment: Math.floor(Math.random() * 500),
        like: Math.floor(Math.random() * 200),
        collect: Math.floor(Math.random() * 50),
        releaseTime: new Date(Date.now() - index * 24 * 60 * 60 * 1000).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        }).replace(/\//g, '-')
    };
}));

// 分页相关
const total = ref(100); // 总数据量
const currentPage = ref(1);
const pageSize = ref(10);

// 计算当前页的数据
const list = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return allList.value.slice(start, end);
});

const handleAuthorClick = (author: string) => {
    console.log(author)
}

const handlePostClick = (id: number) => {
    // router.push(`/forum/details/${id}`)
    window.open(`/forum/details/${id}`, '_blank')
}

const currentSort = ref('最新发布')

const handleSort = (type: string) => {
    switch (type) {
        case 'latest':
            currentSort.value = '最新发布'
            break
        case 'hot':
            currentSort.value = '最热门'
            break
        case 'recommend':
            currentSort.value = '推荐'
            break
    }
}
// 展开评论
const showComments = (id: number) => {
    // 先将所有帖子的showComment设为false
    allList.value.forEach(item => {
        if (item.id !== id) {
            item.showComment = false
        }
    })
    // 找到目标帖子并切换其showComment状态
    const targetPost = allList.value.find(item => item.id === id)
    if (targetPost) {
        targetPost.showComment = !targetPost.showComment
    }
}
const showComplaint = ref(false)
const currentPostId = ref(0)

const openComplaint = (id: number) => {
    currentPostId.value = id
    showComplaint.value = true
}

// 是否为管理员
const isAdmin = ref(true) // 这里可以根据实际情况判断当前用户是否为管理员

// 处理下拉菜单命令
interface CommandPayload {
    type: string;
    id: number;
}

const handleCommand = (command: CommandPayload) => {
    const { type, id } = command
    
    switch (type) {
        case 'changeCategory':
            console.log('修改分类', id)
            // TODO: 实现修改分类逻辑
            break
        case 'addTag':
            console.log('添加标签', id)
            // TODO: 实现添加标签逻辑
            break
        case 'setTop':
            console.log('设为置顶', id)
            // TODO: 实现设为置顶逻辑
            break
        case 'setEssence':
            console.log('设为精华/申请加精', id)
            // TODO: 实现设为精华/申请加精逻辑
            break
        case 'collect':
            console.log('收藏', id)
            // TODO: 实现收藏逻辑
            break
        case 'takeDown':
            console.log('下架', id)
            // TODO: 实现下架逻辑
            break
        case 'complaint':
            console.log('投诉', id)
            // TODO: 实现投诉逻辑，打开投诉弹窗
            openComplaint(id)
            break
        default:
            break
    }
}

// 回复信息
const activeReplyInfo = ref({
    postId: 0,
    commentId: 0,
    replyTo: '',
    replyId: 0 // 添加replyId字段，用于区分回复
})

// 切换回复输入框
const toggleReplyInput = (postId: number, commentId: number, replyTo: string, replyId?: number) => {
    console.log('toggleReplyInput 参数:', { postId, commentId, replyTo, replyId })
    
    // 如果已经是当前回复，则关闭
    if (activeReplyInfo.value.postId === postId && 
        activeReplyInfo.value.commentId === commentId && 
        activeReplyInfo.value.replyTo === replyTo &&
        activeReplyInfo.value.replyId === (replyId || 0)) {
        cancelReply()
        return
    }
    
    // 设置当前回复信息
    activeReplyInfo.value = {
        postId,
        commentId,
        replyTo,
        replyId: replyId || 0
    }
    
    console.log('activeReplyInfo 设置为:', activeReplyInfo.value)
}

// 取消回复
const cancelReply = () => {
    activeReplyInfo.value = {
        postId: 0,
        commentId: 0,
        replyTo: '',
        replyId: 0
    }
}

// 处理评论提交
interface CommentData {
    content: string;
    postId?: number;
    commentId?: number;
    replyTo?: string;
    replyId?: number;
    time: string;
}

const handleCommentSubmit = (data: CommentData) => {
    console.log('提交评论数据:', data)
    
    try {
        // 找到对应的帖子（在当前页的列表中查找）
        const targetPost = list.value.find(item => item.id === data.postId)
        if (!targetPost) {
            throw new Error(`未找到ID为 ${data.postId} 的帖子`)
        }
        
        // 如果是回复评论
        if (data.commentId) {
            const targetComment = targetPost.commentList.find(comment => comment.id === data.commentId)
            if (!targetComment) {
                throw new Error(`未找到ID为 ${data.commentId} 的评论`)
            }
            
            // 确保replies数组存在
            if (!targetComment.replies) {
                targetComment.replies = []
            }
            
            // 生成新回复
            const newReply: Reply = {
                id: Date.now(), // 使用时间戳作为临时ID
                author: '当前用户', // 这里应该使用实际的用户信息
                avatar: '/public/images/avatar.png', // 这里应该使用实际的用户头像
                content: data.content,
                time: data.time,
                likes: 0,
                replyTo: data.replyTo || ''
            }
            
            // 添加回复
            targetComment.replies.push(newReply)
            message.success('回复成功')
        } else {
            // 添加新评论
            const newComment: Comment = {
                id: Date.now(), // 使用时间戳作为临时ID
                author: '当前用户', // 这里应该使用实际的用户信息
                avatar: '/public/images/avatar.png', // 这里应该使用实际的用户头像
                content: data.content,
                time: data.time,
                likes: 0,
                replyTo: '', // 添加缺少的replyTo字段
                replies: []
            }
            
            // 添加评论
            targetPost.commentList.push(newComment)
            message.success('评论成功')
        }
        
        // 关闭回复框
        cancelReply()
    } catch (error) {
        console.error('评论/回复失败:', error)
        message.error(error instanceof Error ? error.message : '评论失败')
    }
}

// 文件下载相关
const showFileDownload = ref(false)
const currentFileUrl = ref('')
const currentFileName = ref('')

// 处理文件点击
const handleFileClick = (fileUrl: string) => {
    console.log('点击文件:', fileUrl)
    currentFileUrl.value = fileUrl
    currentFileName.value = getFileName(fileUrl)
    showFileDownload.value = true
}

// 处理文件下载
const handleFileDownload = (fileUrl: string) => {
    console.log('下载文件:', fileUrl)
    message.success('开始下载文件')
}

// 获取文件名
const getFileName = (fileUrl: string) => {
    return fileUrl.substring(fileUrl.lastIndexOf('/') + 1)
}

// 获取文件图标
const getFileIcon = (fileUrl: string) => {
    const fileName = getFileName(fileUrl)
    const extension = fileName.split('.').pop()?.toLowerCase() || ''
    
    // 根据文件类型返回不同的图标
    switch (extension) {
        case 'pdf':
            return '/public/icon/pdf.png'
        case 'doc':
        case 'docx':
            return '/public/icon/word.png'
        case 'xls':
        case 'xlsx':
            return '/public/icon/excel.png'
        case 'ppt':
        case 'pptx':
            return '/public/icon/ppt.png'
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
        case 'webp':
            return '/public/icon/image.png'
        case 'mp4':
        case 'avi':
        case 'mov':
        case 'wmv':
            return '/public/icon/video.png'
        case 'mp3':
        case 'wav':
        case 'ogg':
            return '/public/icon/audio.png'
        case 'zip':
        case 'rar':
        case '7z':
        case 'tar':
        case 'gz':
            return '/public/icon/zip.png'
        case 'txt':
            return '/public/icon/text.png'
        case 'html':
        case 'css':
        case 'js':
        case 'ts':
        case 'jsx':
        case 'tsx':
        case 'vue':
            return '/public/icon/code.png'
        default:
            return '/public/icon/file.png'
    }
}

</script>
<style scoped lang="scss">
    
</style>
